/**
 * 
 */
package com.hw.TimerDemo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.eos.engine.component.ILogicComponent;
import com.eos.system.annotation.Bizlet;
import com.primeton.ext.engine.component.LogicComponentFactory;

/**
 * @author hewei8
 * @date 2019-01-21 17:41:37
 *
 * 在web.xml里如下配置此servlet，就可以在项目启动时启动定时任务
 * <servlet>
 *		<servlet-name>ServletTimer</servlet-name>
 *		<servlet-class>com.hw.TimerDemo.ServletTimerDemo</servlet-class>
 *		<load-on-startup>1</load-on-startup>
 *	</servlet>
 *	<servlet-mapping>
 *		<servlet-name>ServletTimer</servlet-name>
 *		<url-pattern>*.timer</url-pattern>
 *	</servlet-mapping>
 *
 *
 */



public class ServletTimerDemo extends HttpServlet {
	
	private Timer timer;
	private TimerTask timeTask;
	private MailTaskThread taskThread;
//	private long daySpan = 24 * 60 * 60 * 1000;
	
	// servlet初始化方法，在这里调用方法启动守护线程
	@Override
	public void init() throws ServletException {
		super.init();
		System.out.println("--------------------------------------Servlet任务启动-------------------------------------");
		try {
			mailTaskStart();
		} catch (ParseException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	
	// 启动守护线程
	public void mailTaskStart() throws ParseException{
		
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		
		timer=new Timer();
		timeTask=new SendMailTask();
		taskThread=new MailTaskThread("定时任务",timer,timeTask);
		taskThread.setDaemon(true);
		taskThread.start();
	}
	
	// 守护线程，用来启动定时任务
	class MailTaskThread extends Thread {
		private Timer timer;
		private TimerTask task;
		private long daySpan = 60 * 1000;
		
		public MailTaskThread(String name,Timer timer,TimerTask task) {
			super(name);
			this.task=task;
			this.timer=timer;
		}
		@Override
		public void run() {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 16:35:00");
			
			Date startTime=null;
			try {
				startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));
				// 如果今天的已经过了 首次运行时间就改为明天
		        if (System.currentTimeMillis() > startTime.getTime()){
		            startTime = new Date(startTime.getTime() + daySpan);
		        }
			} catch (ParseException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			
			timer.schedule(task, startTime,daySpan);
			
			super.run();
		}
	}
	
	// 定时任务要执行的功能
	class SendMailTask extends TimerTask{
		
		@Override
		public void run() {
			System.out.println("--------------------------------------定时任务开始执行-------------------------------------");

		}
	}

}
